package user;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: SpringBootDemos
 * @description: 非公平锁
 * @author: Kangsen
 * @create: 2022-05-27 09:49
 **/
@Slf4j
public class NoFairLock {

    //参数 true:公平锁(AQS AbstractQueuedSynchronizer)  false:非公平锁
    ReentrantLock reentrantLock = new ReentrantLock(false);

    /**
     * 非公平锁:未拿到锁的线程阻塞排队,锁释放的时候  队伍中线程竞争获取锁(不是按照排队的顺序获取锁)
     *
     * 公平锁:未拿到锁的线程阻塞排队,并且不允许插队
     */
    //食堂
    private class DiningRoom{
        public void getFood(){
            log.info("{} : 排队中",Thread.currentThread().getName());
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this){
                log.info(" {} : 打饭中",Thread.currentThread().getName());
            }
        }

        public void getReentrantLockFood(){
            try {
                log.info("{} : 排队中",Thread.currentThread().getName());
                reentrantLock.lock();
                log.info(" {} : 打饭中",Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }

    @Test
    public void TestNoFairLock(){
        DiningRoom diningRoom = new DiningRoom();
        //ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                diningRoom.getReentrantLockFood();
            },"编号"+(i+1)).start();
//          threadPoolExecutor.execute(new Thread(()->{
//              diningRoom.getFood();
//          },"编号"+(i+1)));
        }
        //threadPoolExecutor.shutdown();
    }
}
